package com.lucy.viewer.service;

import cn.hutool.core.lang.Validator;
import com.lucy.viewer.config.EditModeConfig;
import com.lucy.viewer.constant.ViewerServiceEnum;
import com.lucy.viewer.params.ViewerFile;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class EditService {
    List<ViewerService> services;

    ViewerFileService viewerFileService;

    EditModeConfig editModeConfig;

    PreviewService previewService;
    /**
     * 获取编辑页面
     * @param documentKey
     * @return ModelAndView
     */
    public ModelAndView loadEditView(String documentKey, HttpServletResponse response) throws IOException {
        // 先查询本地,之后拓展查询接口
        ViewerFile viewerFile = viewerFileService.getViewerFile(documentKey);
        if (Validator.isEmpty(viewerFile)){
            throw new FileNotFoundException();
        }
        String fileType = viewerFile.getFileType();
        ViewerServiceEnum serviceEnum = null;
        switch (fileType){
            case "doc":{
                serviceEnum = editModeConfig.edit_doc();
                break;
            }
            case "docx":{
                serviceEnum = editModeConfig.edit_docx();
                break;
            }
            case "xlsx":{
                serviceEnum = editModeConfig.edit_xlsx();
                break;
            }
            case "xls":{
                serviceEnum = editModeConfig.edit_xls();
                break;
            }
            case "ppt":{
                serviceEnum = editModeConfig.edit_ppt();
                break;
            }
            case "pptx":{
                serviceEnum = editModeConfig.edit_pptx();
                break;
            }
            case "md":{
                serviceEnum = editModeConfig.edit_md();
            }
        }
        if (Validator.isEmpty(serviceEnum)){
            log.info("不支持该文档[{}]编辑-->切换为预览",fileType);
            return previewService.loadPreviewView(documentKey,response);
        }
        for (ViewerService service:services){
            if (service.service().equals(serviceEnum)){
                return service.loadEditorView(documentKey,response);
            }
        }
        return null;
    }
}
